class RealisticDigitalHuman {
    constructor(container) {
        this.container = container;
        this.scene = null;
        this.camera = null;
        this.renderer = null;
        this.human = null;
        this.clock = new THREE.Clock();
        this.isSpeaking = false;
        this.morphTargets = {};
        
        this.init();
        this.animate();
    }

    init() {
        console.log('初始化真实感3D数字人...');
        
        // 创建场景
        this.scene = new THREE.Scene();
        this.scene.background = new THREE.Color(0x87CEEB);
        console.log('场景已创建');

        // 创建相机
        this.camera = new THREE.PerspectiveCamera(
            75,
            window.innerWidth / window.innerHeight,
            0.1,
            1000
        );
        this.camera.position.set(0, 0, 5);
        console.log('相机已创建');

        // 创建渲染器
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.renderer.outputColorSpace = THREE.SRGBColorSpace;
        this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
        this.renderer.toneMappingExposure = 1.2;
        this.renderer.physicallyCorrectLights = true;

        this.container.appendChild(this.renderer.domElement);
        console.log('渲染器已创建并添加到容器');

        // 添加光照
        this.setupLighting();
        console.log('光照已设置');

        // 创建真实感数字人模型
        this.createRealisticHuman();
        console.log('真实感数字人模型已创建');

        // 添加环境
        this.createEnvironment();
        console.log('环境已创建');

        // 窗口大小调整
        window.addEventListener('resize', () => this.onWindowResize());
        
        console.log('真实感3D数字人初始化完成');
    }

    setupLighting() {
        // 环境光
        const ambientLight = new THREE.AmbientLight(0x404040, 0.4);
        this.scene.add(ambientLight);

        // 主光源 - 模拟自然光
        const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2);
        directionalLight.position.set(5, 10, 5);
        directionalLight.castShadow = true;
        directionalLight.shadow.mapSize.width = 4096;
        directionalLight.shadow.mapSize.height = 4096;
        directionalLight.shadow.camera.near = 0.5;
        directionalLight.shadow.camera.far = 50;
        directionalLight.shadow.camera.left = -10;
        directionalLight.shadow.camera.right = 10;
        directionalLight.shadow.camera.top = 10;
        directionalLight.shadow.camera.bottom = -10;
        this.scene.add(directionalLight);

        // 补光 - 模拟环境反射
        const fillLight = new THREE.DirectionalLight(0xffffff, 0.3);
        fillLight.position.set(-5, 0, -5);
        this.scene.add(fillLight);

        // 点光源 - 眼睛高光
        const pointLight = new THREE.PointLight(0xffffff, 0.8, 100);
        pointLight.position.set(0, 2, 3);
        this.scene.add(pointLight);

        // 边缘光 - 增加立体感
        const rimLight = new THREE.DirectionalLight(0xffffff, 0.5);
        rimLight.position.set(-3, 2, -3);
        this.scene.add(rimLight);
    }

    createRealisticHuman() {
        // 创建数字人组
        this.human = new THREE.Group();

        // 创建真实感头部
        this.createRealisticHead();
        
        // 创建性感身材
        this.createSexyBody();
        
        // 创建真实感头发
        this.createRealisticHair();
        
        // 创建真实感眼睛
        this.createRealisticEyes();
        
        // 创建真实感嘴巴
        this.createRealisticMouth();

        this.scene.add(this.human);
    }

    createRealisticHead() {
        // 创建更真实的头部形状
        const headGeometry = new THREE.SphereGeometry(1, 64, 64);
        
        // 修改头部形状，使其更符合真实人脸比例
        const positions = headGeometry.attributes.position;
        for (let i = 0; i < positions.count; i++) {
            const x = positions.getX(i);
            const y = positions.getY(i);
            const z = positions.getZ(i);
            
            // 让脸部更窄，后脑勺更圆
            if (z > 0) {
                positions.setX(i, x * 0.8);
            }
            
            // 让下巴更尖
            if (y < -0.3) {
                positions.setY(i, y * 1.2);
                positions.setZ(i, z * 0.9);
            }
            
            // 让额头更饱满
            if (y > 0.5) {
                positions.setZ(i, z * 1.1);
            }
        }
        positions.needsUpdate = true;
        headGeometry.computeVertexNormals();
        
        // 使用更真实的材质
        const headMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFFE4C4,
            roughness: 0.8,
            metalness: 0.0,
            transparent: true,
            opacity: 0.98
        });
        
        const head = new THREE.Mesh(headGeometry, headMaterial);
        head.position.y = 0.5;
        head.castShadow = true;
        head.receiveShadow = true;
        
        this.human.add(head);
        this.head = head;
        
        // 添加真实感腮红
        this.createRealisticBlush();
        
        // 添加鼻子
        this.createNose();
    }

    createSexyBody() {
        // 创建性感的身材曲线
        const bodyGeometry = new THREE.CylinderGeometry(0.6, 0.4, 2.2, 32);
        
        // 修改身体形状，创造腰线
        const positions = bodyGeometry.attributes.position;
        for (let i = 0; i < positions.count; i++) {
            const y = positions.getY(i);
            const radius = Math.sqrt(positions.getX(i) ** 2 + positions.getZ(i) ** 2);
            
            // 创造腰线效果
            if (y > 0.3 && y < 0.8) {
                const waistFactor = Math.sin((y - 0.3) * Math.PI / 0.5) * 0.3 + 0.7;
                positions.setX(i, positions.getX(i) * waistFactor);
                positions.setZ(i, positions.getZ(i) * waistFactor);
            }
            
            // 胸部曲线
            if (y > 0.8 && y < 1.2) {
                const chestFactor = Math.sin((y - 0.8) * Math.PI / 0.4) * 0.2 + 0.8;
                positions.setX(i, positions.getX(i) * chestFactor);
                positions.setZ(i, positions.getZ(i) * chestFactor);
            }
        }
        positions.needsUpdate = true;
        bodyGeometry.computeVertexNormals();
        
        const bodyMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFFE4C4,
            roughness: 0.7,
            metalness: 0.0
        });
        
        const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
        body.position.y = -0.2;
        body.castShadow = true;
        body.receiveShadow = true;
        
        this.human.add(body);
        this.body = body;
        
        // 创建性感服装
        this.createSexyOutfit();
    }

    createSexyOutfit() {
        // 创建白色飘逸服装
        const outfitGeometry = new THREE.CylinderGeometry(0.8, 1.5, 2.0, 32);
        const outfitMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFFFFFF,
            roughness: 0.3,
            metalness: 0.0,
            transparent: true,
            opacity: 0.9
        });
        
        const outfit = new THREE.Mesh(outfitGeometry, outfitMaterial);
        outfit.position.y = -0.5;
        outfit.castShadow = true;
        outfit.receiveShadow = true;
        
        this.human.add(outfit);
        this.outfit = outfit;
        
        // 添加绿色边饰
        this.createGreenTrim();
    }

    createGreenTrim() {
        // 创建绿色边饰
        const trimGeometry = new THREE.TorusGeometry(0.9, 0.05, 8, 32);
        const trimMaterial = new THREE.MeshStandardMaterial({ 
            color: 0x90EE90,
            roughness: 0.2,
            metalness: 0.1
        });
        
        // 领口边饰
        const neckTrim = new THREE.Mesh(trimGeometry, trimMaterial);
        neckTrim.position.set(0, 0.8, 0);
        neckTrim.rotation.x = Math.PI / 2;
        this.human.add(neckTrim);
        
        // 袖口边饰
        const sleeveTrim1 = new THREE.Mesh(trimGeometry, trimMaterial);
        sleeveTrim1.position.set(-0.7, 0.5, 0);
        sleeveTrim1.rotation.z = Math.PI / 2;
        this.human.add(sleeveTrim1);
        
        const sleeveTrim2 = new THREE.Mesh(trimGeometry, trimMaterial);
        sleeveTrim2.position.set(0.7, 0.5, 0);
        sleeveTrim2.rotation.z = -Math.PI / 2;
        this.human.add(sleeveTrim2);
    }

    createRealisticHair() {
        // 创建更真实的头发
        const hairGeometry = new THREE.SphereGeometry(1.2, 32, 32, 0, Math.PI * 2, 0, Math.PI * 0.7);
        
        // 修改头发形状
        const positions = hairGeometry.attributes.position;
        for (let i = 0; i < positions.count; i++) {
            const y = positions.getY(i);
            const z = positions.getZ(i);
            
            // 让头发更蓬松
            if (y > 0.3) {
                positions.setX(i, positions.getX(i) * 1.1);
                positions.setZ(i, positions.getZ(i) * 1.1);
            }
            
            // 让刘海更自然
            if (z > 0.5 && y > 0.2) {
                positions.setY(i, y + 0.1);
            }
        }
        positions.needsUpdate = true;
        hairGeometry.computeVertexNormals();
        
        const hairMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xD2B48C, // 浅棕色
            roughness: 0.8,
            metalness: 0.0
        });
        
        const hair = new THREE.Mesh(hairGeometry, hairMaterial);
        hair.position.y = 0.8;
        hair.rotation.x = Math.PI * 0.05;
        
        this.human.add(hair);
        this.hair = hair;
        
        // 添加飘逸的发丝
        this.createFloatingHair();
    }

    createFloatingHair() {
        // 创建飘逸的发丝效果
        for (let i = 0; i < 8; i++) {
            const hairStrandGeometry = new THREE.CylinderGeometry(0.02, 0.01, 0.8, 4);
            const hairStrandMaterial = new THREE.MeshStandardMaterial({ 
                color: 0xD2B48C,
                roughness: 0.9,
                metalness: 0.0
            });
            
            const hairStrand = new THREE.Mesh(hairStrandGeometry, hairStrandMaterial);
            hairStrand.position.set(
                (Math.random() - 0.5) * 0.8,
                0.9 + Math.random() * 0.3,
                (Math.random() - 0.5) * 0.4
            );
            hairStrand.rotation.set(
                (Math.random() - 0.5) * 0.5,
                (Math.random() - 0.5) * 0.5,
                (Math.random() - 0.5) * 0.3
            );
            
            this.human.add(hairStrand);
        }
    }

    createRealisticEyes() {
        // 创建真实感的大眼睛
        // 眼白
        const eyeWhiteGeometry = new THREE.SphereGeometry(0.25, 32, 32);
        const eyeWhiteMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFFFFFF,
            roughness: 0.1,
            metalness: 0.0
        });
        
        const leftEyeWhite = new THREE.Mesh(eyeWhiteGeometry, eyeWhiteMaterial);
        leftEyeWhite.position.set(-0.4, 0.6, 0.75);
        leftEyeWhite.scale.set(1.8, 1.2, 0.4);
        
        const rightEyeWhite = leftEyeWhite.clone();
        rightEyeWhite.position.set(0.4, 0.6, 0.75);
        
        this.human.add(leftEyeWhite, rightEyeWhite);
        
        // 虹膜
        const irisGeometry = new THREE.SphereGeometry(0.12, 16, 16);
        const irisMaterial = new THREE.MeshStandardMaterial({ 
            color: 0x8B4513, // 深棕色
            roughness: 0.3,
            metalness: 0.1
        });
        
        const leftIris = new THREE.Mesh(irisGeometry, irisMaterial);
        leftIris.position.set(-0.4, 0.6, 0.85);
        
        const rightIris = leftIris.clone();
        rightIris.position.set(0.4, 0.6, 0.85);
        
        this.human.add(leftIris, rightIris);
        
        // 瞳孔
        const pupilGeometry = new THREE.SphereGeometry(0.06, 16, 16);
        const pupilMaterial = new THREE.MeshStandardMaterial({ 
            color: 0x000000,
            roughness: 0.0,
            metalness: 0.0
        });
        
        const leftPupil = new THREE.Mesh(pupilGeometry, pupilMaterial);
        leftPupil.position.set(-0.4, 0.6, 0.9);
        
        const rightPupil = leftPupil.clone();
        rightPupil.position.set(0.4, 0.6, 0.9);
        
        this.human.add(leftPupil, rightPupil);
        this.leftEye = leftPupil;
        this.rightEye = rightPupil;
        
        // 高光
        const highlightGeometry = new THREE.SphereGeometry(0.04, 8, 8);
        const highlightMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFFFFFF,
            roughness: 0.0,
            metalness: 0.0
        });
        
        const leftHighlight = new THREE.Mesh(highlightGeometry, highlightMaterial);
        leftHighlight.position.set(-0.35, 0.65, 0.95);
        
        const rightHighlight = leftHighlight.clone();
        rightHighlight.position.set(0.45, 0.65, 0.95);
        
        this.human.add(leftHighlight, rightHighlight);
        
        // 睫毛
        this.createEyelashes();
    }

    createEyelashes() {
        // 创建睫毛
        for (let i = 0; i < 6; i++) {
            const lashGeometry = new THREE.CylinderGeometry(0.005, 0.01, 0.15, 4);
            const lashMaterial = new THREE.MeshStandardMaterial({ 
                color: 0x000000,
                roughness: 0.8,
                metalness: 0.0
            });
            
            // 左眼睫毛
            const leftLash = new THREE.Mesh(lashGeometry, lashMaterial);
            leftLash.position.set(-0.4 + (i - 2.5) * 0.08, 0.55, 0.8);
            leftLash.rotation.z = (i - 2.5) * 0.1;
            this.human.add(leftLash);
            
            // 右眼睫毛
            const rightLash = new THREE.Mesh(lashGeometry, lashMaterial);
            rightLash.position.set(0.4 + (i - 2.5) * 0.08, 0.55, 0.8);
            rightLash.rotation.z = -(i - 2.5) * 0.1;
            this.human.add(rightLash);
        }
    }

    createRealisticMouth() {
        // 创建真实感的嘴巴
        const mouthGeometry = new THREE.SphereGeometry(0.12, 16, 16, 0, Math.PI * 2, 0, Math.PI * 0.5);
        const mouthMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFF69B4,
            roughness: 0.2,
            metalness: 0.0
        });
        
        const mouth = new THREE.Mesh(mouthGeometry, mouthMaterial);
        mouth.position.set(0, 0.15, 0.8);
        mouth.rotation.x = Math.PI;
        mouth.scale.set(1.5, 0.8, 0.6);
        
        this.human.add(mouth);
        this.mouth = mouth;
        
        // 添加嘴唇高光
        const lipHighlightGeometry = new THREE.SphereGeometry(0.03, 8, 8);
        const lipHighlightMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFFFFFF,
            roughness: 0.0,
            metalness: 0.0,
            transparent: true,
            opacity: 0.8
        });
        
        const lipHighlight = new THREE.Mesh(lipHighlightGeometry, lipHighlightMaterial);
        lipHighlight.position.set(0, 0.2, 0.85);
        this.human.add(lipHighlight);
    }

    createNose() {
        // 创建鼻子
        const noseGeometry = new THREE.ConeGeometry(0.08, 0.3, 8);
        const noseMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFFE4C4,
            roughness: 0.7,
            metalness: 0.0
        });
        
        const nose = new THREE.Mesh(noseGeometry, noseMaterial);
        nose.position.set(0, 0.4, 0.9);
        nose.rotation.x = Math.PI;
        
        this.human.add(nose);
    }

    createRealisticBlush() {
        // 创建真实感腮红
        const blushGeometry = new THREE.SphereGeometry(0.2, 16, 16);
        const blushMaterial = new THREE.MeshStandardMaterial({ 
            color: 0xFFB6C1,
            transparent: true,
            opacity: 0.4,
            roughness: 0.8,
            metalness: 0.0
        });
        
        const leftBlush = new THREE.Mesh(blushGeometry, blushMaterial);
        leftBlush.position.set(-0.7, 0.25, 0.7);
        leftBlush.scale.set(0.6, 0.4, 0.2);
        
        const rightBlush = leftBlush.clone();
        rightBlush.position.set(0.7, 0.25, 0.7);
        
        this.human.add(leftBlush, rightBlush);
    }

    createEnvironment() {
        // 创建自然的地面
        const groundGeometry = new THREE.PlaneGeometry(30, 30);
        const groundMaterial = new THREE.MeshStandardMaterial({ 
            color: 0x90EE90,
            roughness: 0.8,
            metalness: 0.0
        });
        
        const ground = new THREE.Mesh(groundGeometry, groundMaterial);
        ground.rotation.x = -Math.PI / 2;
        ground.position.y = -2;
        ground.receiveShadow = true;
        
        this.scene.add(ground);

        // 背景装饰
        this.createBackgroundDecorations();
    }

    createBackgroundDecorations() {
        // 添加一些装饰性的几何体
        for (let i = 0; i < 20; i++) {
            const geometry = new THREE.SphereGeometry(0.1, 8, 8);
            const material = new THREE.MeshStandardMaterial({ 
                color: new THREE.Color().setHSL(0.3 + Math.random() * 0.2, 0.7, 0.6),
                roughness: 0.5,
                metalness: 0.0
            });
            
            const decoration = new THREE.Mesh(geometry, material);
            decoration.position.set(
                (Math.random() - 0.5) * 30,
                Math.random() * 8,
                (Math.random() - 0.5) * 30
            );
            
            this.scene.add(decoration);
        }
    }

    startSpeaking(duration = 3) {
        this.isSpeaking = true;
        
        // 嘴巴动画
        this.animateMouth(duration);
        
        // 头部轻微摆动
        this.animateHead(duration);
        
        // 眼睛眨眼
        this.animateBlinking(duration);
    }

    stopSpeaking() {
        this.isSpeaking = false;
        
        // 重置嘴巴位置
        if (this.mouth) {
            gsap.to(this.mouth.scale, {
                duration: 0.3,
                y: 0.8,
                ease: "power2.out"
            });
        }
    }

    animateMouth(duration) {
        if (!this.mouth) return;
        
        const tl = gsap.timeline({ repeat: -1 });
        
        tl.to(this.mouth.scale, {
            duration: 0.1,
            y: 1.2,
            ease: "power2.inOut"
        })
        .to(this.mouth.scale, {
            duration: 0.1,
            y: 0.8,
            ease: "power2.inOut"
        })
        .to(this.mouth.scale, {
            duration: 0.15,
            y: 1.0,
            ease: "power2.inOut"
        })
        .to(this.mouth.scale, {
            duration: 0.1,
            y: 0.8,
            ease: "power2.inOut"
        });
        
        // 停止说话时清除动画
        setTimeout(() => {
            tl.kill();
            this.stopSpeaking();
        }, duration * 1000);
    }

    animateHead(duration) {
        if (!this.head) return;
        
        const tl = gsap.timeline({ repeat: -1 });
        
        tl.to(this.head.rotation, {
            duration: 0.8,
            y: 0.05,
            ease: "power2.inOut"
        })
        .to(this.head.rotation, {
            duration: 0.8,
            y: -0.05,
            ease: "power2.inOut"
        });
        
        setTimeout(() => {
            tl.kill();
            gsap.to(this.head.rotation, {
                duration: 0.5,
                y: 0,
                ease: "power2.out"
            });
        }, duration * 1000);
    }

    animateBlinking(duration) {
        if (!this.leftEye || !this.rightEye) return;
        
        const blink = () => {
            gsap.to([this.leftEye.scale, this.rightEye.scale], {
                duration: 0.1,
                y: 0.1,
                ease: "power2.inOut",
                onComplete: () => {
                    gsap.to([this.leftEye.scale, this.rightEye.scale], {
                        duration: 0.1,
                        y: 1,
                        ease: "power2.inOut"
                    });
                }
            });
        };
        
        // 定期眨眼
        const blinkInterval = setInterval(blink, 2000);
        
        setTimeout(() => {
            clearInterval(blinkInterval);
        }, duration * 1000);
    }

    updateControls(rotationSpeed, animationIntensity, expressionIntensity) {
        // 更新旋转速度
        this.rotationSpeed = rotationSpeed;
        
        // 更新动画强度
        this.animationIntensity = animationIntensity;
        
        // 更新表情强度
        this.expressionIntensity = expressionIntensity;
    }

    animate() {
        requestAnimationFrame(() => this.animate());
        
        const elapsedTime = this.clock.getElapsedTime();
        
        // 缓慢旋转
        if (this.human) {
            this.human.rotation.y += (this.rotationSpeed || 1) * 0.003;
        }
        
        // 呼吸动画
        if (this.body) {
            this.body.scale.y = 1 + Math.sin(elapsedTime * 1.5) * 0.015 * (this.animationIntensity || 1);
        }
        
        // 头发轻微摆动
        if (this.hair) {
            this.hair.rotation.y = Math.sin(elapsedTime * 1.2) * 0.03 * (this.animationIntensity || 1);
        }
        
        // 服装飘动效果
        if (this.outfit) {
            this.outfit.rotation.y = Math.sin(elapsedTime * 0.8) * 0.02 * (this.animationIntensity || 1);
        }
        
        this.renderer.render(this.scene, this.camera);
    }

    onWindowResize() {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(window.innerWidth, window.innerHeight);
    }

    dispose() {
        if (this.renderer) {
            this.renderer.dispose();
        }
        if (this.container && this.renderer) {
            this.container.removeChild(this.renderer.domElement);
        }
    }
}
